package com.res.simulator.handler;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.res.common.handler.CommonHandler;
import com.res.simulator.model.GenericAPIExecutionModel;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.simulator.transformer.APIInvocationTransformer;
import com.res.simulator.view.ResultView;
import com.res.system.utils.SimulatorUtilities;
import com.res.system.utils.SimulatorUtilities.ConfigData;
import com.sip.comserver.communication.CommunicationMessage;

public class APIInvocationHandler implements CommonHandler<ResultView, GenericAPIExecutionModel> {

    private static final Logger logger = Logger.getLogger(APIInvocationHandler.class);

    public ResultView process(final GenericAPIExecutionModel model) throws Exception {

        final APIInvocationTransformer restTransformer = new APIInvocationTransformer();
        final Map<String, Object> domainMap = restTransformer.transformModelToDomian(model);

        final Map<String, Object> returnMap = commit(domainMap);
        
        ResultView resultView;
        
        if(!returnMap.containsKey("ERROR")){
            
            resultView = restTransformer.transformDomianToView(returnMap);
            
        }else {
            
            resultView =new ResultView();
            
            resultView.setApiName(model.getApiName());
            resultView.setInputParams("ERROR !!!");
            resultView.setResult(((Exception)returnMap.get("ERROR")).toString());
        }

        return resultView;
    }

    private Map<String, Object> commit(final Map<String, Object> domainMap) throws Exception {

        final CommunicationMessage message = new CommunicationMessage();

        final String serverAddress = SimulatorUtilities.getConfigData(ConfigData.SERVER_ADDRESS);
        final String port = SimulatorUtilities.getConfigData(ConfigData.SERVER_PORT);

        logger.info("Message Header==>" + "JOBType:cm" + "|ID:" + serverAddress + "|Port:" + port + "|Executor:serviceExecutorREST");

        message.setMessageHeader("JOBType:APISubmitCall|Executor:ServiceExecutorREST|ID:" + serverAddress + "|Port:" + port);

        message.setObject(domainMap);

        final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
        final CommunicationMessage returnedMessage = plugin.invoke(message);

        if(returnedMessage.getObject() instanceof Exception){
            
            Map<String,Object> errorMap =new HashMap<String, Object>();
            errorMap.put("ERROR", returnedMessage.getObject());
            
            return errorMap;
        }
        
        final Map<String, Object> returnMap = (Map<String, Object>) returnedMessage.getObject();

        return returnMap;

    }

}
